<template>
  <!-- 分组管理对话框 -->
  <el-dialog title="分组管理" :visible.sync="groupDialogVisible" width="70%">
    <div class="group-manage-container">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" icon="el-icon-plus" @click="showAddGroupDialog">新增分组</el-button>
        <el-button type="danger" icon="el-icon-delete" :disabled="!selectedGroups.length" @click="batchDeleteGroups">
          批量删除
        </el-button>
      </div>

      <!-- 分组表格 -->
      <el-table
        :data="groups"
        style="width: 100%"
        @selection-change="handleGroupSelectionChange"
        row-key="id"
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="分组名称" width="200">
          <template #default="{row}">
            <span v-if="!row.editing">{{ row.name }}</span>
            <el-input
              v-else
              v-model="row.editName"
              size="small"
              @keyup.enter.native="saveGroupEdit(row)"
              @blur="saveGroupEdit(row)"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="memberCount" label="成员数量" width="120">
          <template #default="{row}">
            <el-tag>{{ row.memberCount || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="120">
          <template #default="{row}">
            <span v-if="!row.editing">{{ row.sort }}</span>
            <el-input-number
              v-else
              v-model="row.editSort"
              :min="0"
              :max="999"
              size="small"
              style="width: 100px"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="250"></el-table-column>
        <el-table-column label="操作" width="600">
          <template #default="{row}">
            <el-button size="mini" @click="showMemberDialog(row)">成员管理</el-button>
            <el-button size="mini" @click="showAddMemberDialog(row)">添加成员</el-button>
            <el-button size="mini" type="primary" @click="editGroup(row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="deleteGroup(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加分组对话框 -->
    <el-dialog title="添加分组" :visible.sync="addGroupDialogVisible" width="500px" append-to-body>
      <el-form :model="groupForm" :rules="groupRules" ref="groupForm" label-width="80px">
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入分组名称"></el-input>
        </el-form-item>
        <el-form-item label="父分组" prop="parentId">
          <el-cascader
            v-model="groupForm.parentId"
            :options="groupOptions"
            :props="{ checkStrictly: true, value: 'id', label: 'name', children: 'children', emitPath: false }"
            clearable
            placeholder="不选则为一级分组"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="groupForm.sort"
            :controls-position="'right'"
            :min="0"
            :max="999"
            label="排序值"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addGroupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitGroupForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加成员对话框 -->
    <el-dialog title="添加成员" :visible.sync="addMemberDialogVisible" width="70%" append-to-body>
      <div class="member-select-container">
        <div class="member-list">
          <el-table
            :data="availableMembers"
            style="width: 100%"
            @selection-change="handleMemberSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column prop="userName" label="姓名" width="180">
              <template #default="{row}">
                <div class="user-info">
                  <el-avatar :size="30" :src="row.avatar"></el-avatar>
                  <span style="margin-left: 10px;">{{ row.userName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="role" label="角色" width="120">
              <template #default="{row}">
                <el-tag :type="row.role === 1 ? 'danger' : row.role === 2 ? 'warning' : ''">
                  {{ formatRole(row.role) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="joinTime" label="加入时间"></el-table-column>
          </el-table>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="addMemberDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddMembers">确定</el-button>
      </div>
    </el-dialog>

    <!-- 查看成员对话框 -->
    <el-dialog title="分组成员管理" :visible.sync="memberDialogVisible" width="70%" append-to-body>
      <div class="member-manage-container">
        <!-- 工具栏 -->
        <div class="toolbar">
          <el-button
            type="danger"
            icon="el-icon-delete"
            :disabled="selectedMembers.length === 0"
            @click="batchRemoveMembers"
          >
            批量移除
          </el-button>
          <div class="search-box">
            <el-input
              v-model="memberSearchKey"
              placeholder="搜索成员"
              prefix-icon="el-icon-search"
              clearable
              @clear="loadMembers"
              @keyup.enter.native="loadMembers"
            ></el-input>
          </div>
        </div>

        <!-- 成员表格 -->
        <el-table
          :data="filteredMembers"
          style="width: 100%"
          @selection-change="handleMemberSelectionChange"
          v-loading="memberLoading"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="userName" label="姓名" width="180">
            <template #default="{row}">
              <div class="user-info">
                <el-avatar :size="30" :src="row.avatar"></el-avatar>
                <span style="margin-left: 10px;">{{ row.userName }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="joinTime" label="加入时间" width="250"></el-table-column>
          <el-table-column prop="role" label="角色" width="120">
            <template #default="{row}">
              <el-tag :type="row.role === 1 ? 'danger' : row.role === 2 ? 'warning' : ''">
                {{ formatRole(row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{row}">
              <el-button
                size="mini"
                type="danger"
                @click="removeMember(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          @size-change="handleMemberSizeChange"
          @current-change="handleMemberPageChange"
          :current-page="memberQuery.pageNum"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="memberQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="memberTotal"
        ></el-pagination>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  getExamSubgroups,
  addExamSubgroup,
  updateExamSubgroup,
  deleteExamSubgroup,
  getGroupMembers,
  addSubgroupMembers,
  removeSubgroupMembers,
  getSubgroupMembers
} from '@/api/exam/subGroup'

export default {
  props: {
    groupId: {
      type: [Number, String],
      required: true
    },
    members: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 成员管理相关数据
      memberDialogVisible: false,
      // currentSubgroup: null,
      membersSubgroups: [],
      filteredMembers: [],
      // selectedMembers: [],
      memberSearchKey: '',
      memberLoading: false,
      memberQuery: {
        pageNum: 1,
        pageSize: 10
      },
      memberTotal: 0,
      groupDialogVisible: false,
      addGroupDialogVisible: false,
      addMemberDialogVisible: false,
      groups: [],
      selectedGroups: [],
      selectedMembers: [],
      currentGroup: null,  // 当前操作的分组（统一使用这个变量）
      currentSubgroup: null, // 可以移除，统一使用currentGroup
      groupForm: {
        name: '',
        parentId: null
      },
      groupRules: {
        name: [
          { required: true, message: '请输入分组名称', trigger: 'blur' },
          { max: 50, message: '长度不超过50个字符', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请输入排序值', trigger: 'blur' },
          { type: 'number', message: '排序必须为数字值', trigger: 'blur' }
        ]
      },
      availableMembers: [],
      groupOptions: []
    }
  },
  computed: {
    // 格式化角色显示
    formatRole() {
      return (role) => ['', '主要负责人', '次要负责人', '考生'][role] || ''
    }
  },
  methods: {

    // 查看分组成员
    async showMemberDialog(subgroup) {
      this.currentSubgroup = subgroup
      this.memberDialogVisible = true
      this.memberQuery.pageNum = 1
      await this.loadMembers()
    },
    // 加载成员列表
    async loadMembers() {
      this.memberLoading = true
      try {
        const res = await getSubgroupMembers({
          subgroupId: this.currentSubgroup.id,
          pageNum: this.memberQuery.pageNum,
          pageSize: this.memberQuery.pageSize,
          searchKey: this.memberSearchKey
        })
        this.membersSubgroups = res.rows
        this.memberTotal = res.total
        this.filteredMembers = res.rows
      } catch (error) {
        this.$message.error('加载成员失败: ' + error.message)
      } finally {
        this.memberLoading = false
      }
    },
// 批量移除成员
    batchRemoveMembers() {
      if (this.selectedMembers.length === 0) {
        this.$message.warning('请选择要移除的成员')
        return
      }

      this.$confirm(`确定要移除选中的 ${this.selectedMembers.length} 个成员吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await removeSubgroupMembers({
            subgroupId: this.currentSubgroup.id,
            userIds: this.selectedMembers.map(m => m.userId)
          })
          this.$message.success('移除成功')
          this.selectedMembers = []
          await this.loadMembers()
        } catch (error) {
          this.$message.error('移除失败: ' + error.message)
        }
      }).catch(() => {})
    },

    // 单独移除成员
    removeMember(row) {
      this.$confirm(`确定要移除成员 ${row.userName} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await removeSubgroupMembers({
            subgroupId: this.currentSubgroup.id,
            userIds: [row.userId]
          })
          this.$message.success('移除成功')
          await this.loadMembers()
        } catch (error) {
          this.$message.error('移除失败: ' + error.message)
        }
      }).catch(() => {})
    },
    // 成员分页大小变化
    handleMemberSizeChange(val) {
      this.memberQuery.pageSize = val
      this.loadMembers()
    },

    // 成员页码变化
    handleMemberPageChange(val) {
      this.memberQuery.pageNum = val
      this.loadMembers()
    },

    // 显示分组管理对话框
    showGroupDialog() {
      this.groupDialogVisible = true
      this.loadGroups()
    },

    // 加载分组数据
    async loadGroups() {
      try {
        const res = await getExamSubgroups(this.groupId)
        this.groups = this.buildTree(res.rows)
        this.groupOptions = this.buildTree(res.rows)
      } catch (error) {
        this.$message.error('加载分组失败: ' + error.message)
      }
    },

    // 构建树形结构
    buildTree(data) {
      const tree = []
      const map = {}

      data.forEach(item => {
        map[item.id] = { ...item, children: [] }
      })

      data.forEach(item => {
        if (item.parentId) {
          if (map[item.parentId]) {
            map[item.parentId].children.push(map[item.id])
          }
        } else {
          tree.push(map[item.id])
        }
      })

      return tree
    },

    // 显示添加分组对话框
    showAddGroupDialog() {
      this.addGroupDialogVisible = true
      this.groupForm = {
        name: '',
        parentId: null,
        sort: 0
      }
      this.$nextTick(() => {
        this.$refs.groupForm?.clearValidate()
      })
    },

    // 提交分组表单
    async submitGroupForm() {
      try {
        await this.$refs.groupForm.validate()
        const sortValue = Number.isInteger(this.groupForm.sort) ? this.groupForm.sort : 0
        const params = {
          examGroupId: this.groupId,
          name: this.groupForm.name,
          parentId: this.groupForm.parentId || null,
          sort: sortValue
        }

        await addExamSubgroup(params)
        this.$message.success('添加分组成功')
        this.addGroupDialogVisible = false
        await this.loadGroups()
      } catch (error) {
        console.error(error)
      }
    },

    // 编辑分组
    editGroup(row) {
      this.$set(row, 'editing', true)
      this.$set(row, 'editName', row.name)
      this.$set(row, 'editSort', row.sort) // 添加排序编辑
    },

    // 保存分组编辑
    async saveGroupEdit(row) {
      try {
        if (!row.editName || row.editName.trim() === '') {
          this.$message.warning('分组名称不能为空')
          return
        }

        const sortValue = Number.isInteger(row.editSort) ? row.editSort : 0

        await updateExamSubgroup({
          id: row.id,
          name: row.editName
        })

        this.$message.success('修改成功')
        row.name = row.editName
        row.editing = false
      } catch (error) {
        this.$message.error('修改失败: ' + error.message)
      }
    },

    // 删除分组
    deleteGroup(row) {
      this.$confirm('确定要删除该分组吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await deleteExamSubgroup(row.id)
          this.$message.success('删除成功')
          this.loadGroups()
        } catch (error) {
          this.$message.error('删除失败: ' + error.message)
        }
      }).catch(() => {})
    },

    // 批量删除分组
    batchDeleteGroups() {
      if (!this.selectedGroups.length) return

      this.$confirm(`确定要删除选中的 ${this.selectedGroups.length} 个分组吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedGroups.map(item => item.id)
          await deleteExamSubgroup(ids)
          this.$message.success('删除成功')
          this.loadGroups()
          this.selectedGroups = []
        } catch (error) {
          this.$message.error('删除失败: ' + error.message)
        }
      }).catch(() => {})
    },

    // // 显示添加成员对话框
    async showAddMemberDialog(group = null) {
      try {
        // 确定当前分组，如果从成员管理打开则使用currentSubgroup，否则使用传入的group
        const targetGroup = group || this.currentSubgroup;
        if (!targetGroup) {
          this.$message.warning('请先选择分组');
          return;
        }

        this.currentGroup = targetGroup;
        this.addMemberDialogVisible = true;

        // 获取所有考生成员（role=3）
        const allStudents = this.members.filter(m => m.role === 3);

        // 获取已在当前分组的成员
        const res = await getGroupMembers(targetGroup.id);
        const currentMemberIds = res.rows.map(m => m.userId);

        // 过滤出可添加的成员（不在当前分组中的考生）
        this.availableMembers = allStudents.filter(m =>
          !currentMemberIds.includes(m.userId)
        );

        // 重置选中状态
        this.selectedMembers = [];

        // 如果有搜索关键词，进行过滤
        if (this.memberSearchKey) {
          const keyword = this.memberSearchKey.toLowerCase();
          this.availableMembers = this.availableMembers.filter(m =>
            m.userName.toLowerCase().includes(keyword) ||
            (m.userAccount && m.userAccount.toLowerCase().includes(keyword))
          );
        }
      } catch (error) {
        this.$message.error('加载可添加成员失败: ' + (error.message || error));
        console.error('加载可添加成员失败:', error);
      }
    },

    // 提交添加成员
    async submitAddMembers() {
      if (!this.selectedMembers.length) {
        this.$message.warning('请选择要添加的成员')
        return
      }

      try {
        const params = {
          subgroupId: this.currentGroup.id,
          userIds: this.selectedMembers.map(m => m.userId)
        }

        await addSubgroupMembers(params)
        this.$message.success('添加成员成功')
        this.addMemberDialogVisible = false
        this.loadGroups()
      } catch (error) {
        this.$message.error('添加成员失败: ' + error.message)
      }
    },

    // 分组选择变化
    handleGroupSelectionChange(val) {
      this.selectedGroups = val
    },

    // 成员选择变化
    handleMemberSelectionChange(val) {
      this.selectedMembers = val
    }
  }
}
</script>

<style scoped>
.group-manage-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.toolbar {
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
}

.member-select-container {
  display: flex;
}

.member-list {
  flex: 1;
  margin-right: 20px;
}

.member-selected {
  flex: 0 0 300px;
  border-left: 1px solid #eee;
  padding-left: 20px;
}



.member-manage-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.search-box {
  width: 300px;
}

.user-info {
  display: flex;
  align-items: center;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
